import DeviceTemplate from "@/components/DeviceTemplate";
import React, { useState } from 'react';
import { Image, StyleSheet, Text, View, Modal, TouchableOpacity } from 'react-native';
import { useNavigation } from 'expo-router';
import { useAudioPlayer } from 'expo-audio';
import VitalCapacityParser from '../../utils/VitalCapacityParser';

interface GuideTextComponentProps {
    type?: string
}

const VitalCapacityDevice: React.FC = () => {
    const [showCompletionDialog, setShowCompletionDialog] = useState(false);
    const navigation = useNavigation();
    
    // 使用 useAudioPlayer hook 创建音频播放器
    const audioSource = require('../../assets/mp3/notice.mp3');
    const player = useAudioPlayer(audioSource);

    // 判断肺活量检测是否完成
    const isVitalCapacityTestComplete = (measurement: any): boolean => {
        if (!measurement || typeof measurement.value !== 'number') return false;
        // 肺活量检测完成条件：基于报文中的完成标志位
        // 如果解析结果中包含isComplete标志且为true，表示检测完成
        if (measurement.isComplete === true) {
            return true;
        }
        // 兜底条件：有有效的肺活量值
        return !isNaN(measurement.value) && measurement.value > 1000;
    };

    const playNotificationSound = () => {
        try {
            // 重置到开头并播放
            player.seekTo(0);
            player.play();
        } catch (error) {
            console.error('Error playing sound:', error);
        }
    };



    const handleTestComplete = () => {
        // 显示检测完成提示对话框
        setShowCompletionDialog(true);
        // 播放完成提示音
        playNotificationSound();
    };
    
    // 重置肺活量检测状态
    const resetVitalCapacityDetection = () => {
        // 这里我们无法直接访问DeviceTemplate中的模块级变量
        // 但我们可以通过重新挂载组件来重置状态
        // 在实际使用中，用户点击"继续检测"会自然地开始新的检测流程
    };

    const finishTest = () => {
        setShowCompletionDialog(false);
        navigation.goBack();
    };

    const GuideImageComponent = () => (
        <View style={styles.imageContainer}>
            <Image
                source={require('../../assets/images/vitalcapacity.jpg')}
                style={styles.image}
                resizeMode="stretch"
            />
        </View>
    );

    const GuideTextComponent = ({type}: GuideTextComponentProps) => (
        <View style={styles.guideTextContainer}>
            <Text style={styles.guideTitle}>肺活量检测操作指南</Text>
            <Text style={styles.guideStep}>1. 连接设备，等待指示灯变为绿色</Text>
            <Text style={styles.guideStep}>2. 点击&#34;开始检测&#34;按钮</Text>
            <Text style={styles.guideStep}>3. 深吸一口气，然后对着检测口用力吹气</Text>
            <Text style={styles.guideStep}>4. 尽可能将肺部的气体全部呼出</Text>
            <Text style={styles.guideStep}>5. 查看测量结果</Text>
            <Text style={styles.guideTip}>提示：测量前请先休息片刻，保持呼吸平稳</Text>
        </View>
    );

    return (
        <>
            <DeviceTemplate
                deviceName="肺活量检测仪"
                deviceNamePrefix="ETEPT"
                serviceUUID={VitalCapacityParser.SERVICE_UUID}
                commandServiceUUID={VitalCapacityParser.SERVICE_UUID}
                dataCharacteristic={VitalCapacityParser.DATA_CHARACTERISTIC}
                commandCharacteristic={VitalCapacityParser.COMMAND_CHARACTERISTIC}
                withResp={false}
                stopCommand={VitalCapacityParser.STOP_COMMAND}
                startCommand={VitalCapacityParser.START_COMMAND}
                parser={{
                    parseData: VitalCapacityParser.parseData,
                }}
                deviceRoute="VitalCapacity"
                onTestComplete={handleTestComplete}
            >
                <GuideTextComponent type="guideText"/>
                <GuideImageComponent/>
            </DeviceTemplate>
            
            {/* 检测完成提示对话框 */}
            {showCompletionDialog && (
                <View style={styles.dialogOverlay}>
                    <View style={styles.dialogContainer}>
                        <Text style={styles.dialogTitle}>检测完成</Text>
                        <Text style={styles.dialogMessage}>您的检测已完成并已自动保存结果</Text>
                        <View style={styles.dialogButtons}>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.stayButton]}
                                onPress={() => {
                                    // 重置检测完成状态，允许下次继续检测
                                    setShowCompletionDialog(false);
                                }}
                            >
                                <Text style={styles.stayButtonText}>继续检测</Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.dialogButton, styles.returnButton]}
                                onPress={finishTest}
                            >
                                <Text style={styles.returnButtonText}>返回</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            )}
        </>
    );
};

const styles = StyleSheet.create({
    imageContainer: {
        width: '100%',
        alignItems: 'center',
        marginBottom: 15,
    },
    image: {
        width: '100%',
        height: 300,
        backgroundColor: 'black',
        borderRadius: 8,
    },
    guideTextContainer: {
        width: '100%',
        padding: 10,
    },
    guideTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#0a7ea4',
        marginBottom: 15,
        textAlign: 'center',
    },
    guideStep: {
        fontSize: 14,
        color: '#333',
        marginBottom: 8,
        lineHeight: 20,
    },
    guideTip: {
        fontSize: 14,
        color: '#0a7ea4',
        fontStyle: 'italic',
        marginTop: 10,
    },
    // 检测完成提示对话框样式
    dialogOverlay: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        justifyContent: 'center',
        alignItems: 'center',
        zIndex: 1000,
    },
    dialogContainer: {
        backgroundColor: 'white',
        borderRadius: 12,
        padding: 24,
        width: '80%',
        maxWidth: 320,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {width: 0, height: 2},
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
    },
    dialogTitle: {
        fontSize: 20,
        fontWeight: 'bold',
        color: '#333',
        marginBottom: 16,
    },
    dialogMessage: {
        fontSize: 16,
        color: '#666',
        textAlign: 'center',
        marginBottom: 24,
    },
    dialogButtons: {
        flexDirection: 'row',
        width: '100%',
        justifyContent: 'space-between',
    },
    dialogButton: {
        flex: 1,
        paddingVertical: 12,
        paddingHorizontal: 16,
        borderRadius: 8,
        alignItems: 'center',
        marginHorizontal: 8,
    },
    stayButton: {
        backgroundColor: '#f0f0f0',
    },
    returnButton: {
        backgroundColor: '#0a7ea4',
    },
    stayButtonText: {
        fontSize: 16,
        color: '#333',
        fontWeight: 'bold',
    },
    returnButtonText: {
        fontSize: 16,
        color: 'white',
        fontWeight: 'bold',
    }
});

export default VitalCapacityDevice;
